﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace VolunteerHubAdapter.MVVM.Commands
{
   public class RelayCommand : System.Windows.Input.ICommand
    {
        #region Fields

        readonly Action<object> _execute;
        readonly Predicate<object> _canExecute;

        #endregion // Fields

        #region Constructors

        /// <summary>
        /// Creates a new command that can always execute.
        /// </summary>
        /// <param name="execute">The execution logic.</param>
        public RelayCommand(Action<object> execute)
            : this(execute, null)
        {
        }

        /// <summary>
        /// Creates a new command.
        /// </summary>
        /// <param name="execute">The execution logic.</param>
        /// <param name="canExecute">The execution status logic.</param>
        public RelayCommand(Action<object> execute, Predicate<object> canExecute)
        {
            if (execute == null)
                throw new ArgumentNullException("execute");

            _execute = execute;
            _canExecute = canExecute;
        }

        #endregion // Constructors

        #region ICommand Members
        [System.Diagnostics.DebuggerStepThrough]
        public bool CanExecute(object parameter)
        {
            return _canExecute == null ? true : _canExecute(parameter);
        }

        private EventHandler _canExecuteChanged; //caching the handlers WPF is adding to the RequerySuggested event so that we can fire those handlers as we please
        public event EventHandler CanExecuteChanged
        {
            add 
            {
                System.Windows.Input.CommandManager.RequerySuggested += value;
                _canExecuteChanged += value;
            }
            remove 
            { 
                System.Windows.Input.CommandManager.RequerySuggested -= value;
                _canExecuteChanged -= value;
            }
        }

        public void Execute(object parameter)
        {
            _execute(parameter);
        }

        #endregion // ICommand Members

       /// <summary>
       /// Fires the WPF handlers that are looking to evaluating CanExecute
       /// </summary>
       public void RefreshCanExecute()
        {
            if(_canExecuteChanged != null) _canExecuteChanged(this, EventArgs.Empty);
        }
    }
}
